<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Pay;
use app\common\model\Banner;
use app\common\model\cancel\Level;
use app\common\model\Cart;
use app\common\model\Category;
use app\common\model\forest\Member;
use app\common\model\forest\Order;
use app\common\model\Goods;
use app\common\model\User;
use app\common\model\user\Address;
use think\Db;
use think\Queue;

/**
 * 森林会员接口
 * @ApiInternal
 */
class Forest extends Api
{
    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];

    /**
     * 森林会员信息
     *
     */
    public function index()
    {
        $data['rules'] = config('site.rules');
        $data['s_introduction'] = config('site.s_introduction');
        $data['category'] = Category::all(['type' => 'forest']);
        $data['goodsList'] = Member::getForestMemberList($this->auth->id);
        $this->success('', $data);
    }
    /**
     * 订单下单预览
     *
     */
    public function yuOrder()
    {
        $get = request()->get();
        $uid =  $this->auth->id;
        extract($get);
        if (!isset($goods_id) || empty($goods_id)) {
            $this->error('参数错误');
        }
        $userNum = User::where('forest_level',  $goods_id)->where('validitytime', '>', time())->count();
        $member = Member::get($goods_id);
        if ($userNum >= $member['num']) {
            $this->error('名额已满，可购买其他森林会员');
        }
        $userInfo = $this->auth->getUserinfo();
        if ($userInfo['forest_level'] >= $goods_id && !$userInfo['is_expires']) {
            $this->error('当前会员等级大于购买会员登录');
        }
        $order = new Order();
        $data = $order->yuOrder($goods_id, $address_id ?? 0, $uid);
        $data['plant'] = $plant ?? 0;
        $data['pay_type'] = $pay_type ?? 0;
        cache('forest_' . $uid, $data, '900');
        $this->success('', $data);
    }
    /**
     * 订单统一下单
     *
     */
    public function addOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $uid = $this->auth->id;
        $data = cache('forest_' . $uid);
        if(!$data){
            $this->error('请重新下单');
        }
        extract($data);
        if (!$data) {
            $this->error('订单已失效，请重新选择商品');
        }
        if ($plant == '0') {
            if (!isset($address_id) || empty($address_id)) {
                $this->error('收货地址不能为空');
            }
        }
        if (!isset($pay_type)) {
            $this->error('请选择支付方式');
        }
        Db::startTrans();
        try {
            //添加订单商品信息
            $order = new Order();
            $order_id = $order->addData($data, $uid);
            if (!$order_id) {
                exception('下单失败');
            }
            $total_order = Order::get($order_id);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return self::error($e->getMessage());
        }
        Queue::later(900, 'app\common\job\Forest', $total_order, 'forest');
        cache('forest_' . $uid, null);
        return $this->success('下单成功', $order_id);
    }
    /**
     * 立即付款
     *
     */
    public function pay()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        try {
            $order = Order::get($id);
            if ($order['pay_price'] <= 0) {
                exception('支付失败');
            } else {
                $data['title'] = $order['name'];
                $data['sn'] = $order['sn'];
                $data['pay_money'] = $order['pay_price'];
                $data['user_id'] = $order['user_id'];
                if ($order['pay_type'] == '0') {
                    $sdk = Pay::wxpay($data, 'order');
                } elseif ($order['pay_type'] == '1') {

                    $sdk = Pay::alipay($data);
                } else {
                    //余额支付
                    $sdk =  Pay::yue($data);
                }
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('支付成功', $sdk);
    }
    /**
     * 会员开通记录
     *
     */
    public function openingRecord()
    {
        $order = Order::where(['user_id' => $this->auth->id, 'status' => 1])->order('id desc')->select();
        $this->success('', $order);
    }
    /**
     * 判断是否能取消会员
     *
     */
    public function checkCancel()
    {
        $userInfo = $this->auth->getUserinfo();
        $userInfo['validitytime'];
        $years = strtotime('-2 years', $userInfo['validitytime']);
        $date = strtotime('-3 years', $userInfo['validitytime']);
        if ($years < time()) {
            $this->error(date('Y年m月d日', $date), null, -1);
        }
        $this->success();
    }
    /**
     * 取消会员
     *
     */
    public function cancelLevel()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = request()->post();
        extract($post);
        if (!isset($type)) {
            $this->error('请选择取消方式');
        }
        $contact =  $telephone = $address = '';
        if ($type != 2) {
            if (!isset($address_id) || empty($address_id)) {
                $this->error('请选择收货地址');
            }
            $addressInfo = Address::get($address_id);
            $contact = $addressInfo['contact'];
            $telephone = $addressInfo['telephone'];
            $address = $addressInfo['province'] ?? '' . '/' . $addressInfo['city'] ?? '' . '/' . $addressInfo['district'] ?? '' . '/' . $addressInfo['address'] ?? '';
        }
        $level = Level::get(['user_id' => $this->auth->id]);
        $user = User::get(['forest_level' => ['>', '0'], 'validitytime' => ['>', time()]]);
        if ($user) {
            if (isset($level) && $level->status == 0) {
                $this->error('待审核');
            }
        } else {
            $this->error('会员不存在');
        }
        $data = [
            'user_id' => $this->auth->id,
            'address_id' => $address_id,
            'consignee' => $contact,
            'phone' => $telephone,
            'address' => $address,
            'type' => $type,
            'canceltime' => time(),
        ];
        $cancel = new Level($data);
        $cancel->save();
        $this->success('提交成功');
    }
}
